<template>
  <div>
    <el-form  :inline="true"  label-width="68px" >
      <el-form-item label="用户名">
        <el-input v-model="query.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
            type="primary"
            plain
            :icon="Plus"
            size="mini"
            @click="handleAdd"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <div style="padding-top: 10px">
      <el-table v-loading="loading" :data="list" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <el-table-column prop="username" label="用户名"  />
<!--        <el-table-column prop="phone" label="手机号"  />-->
        <el-table-column prop="nickname" label="昵称"  />
        <el-table-column prop="roleName" label="角色"  />
        <el-table-column prop="sex" label="性别"  />
        <el-table-column label="头像">
          <template #default="scope">
            <img :src="scope.row.avatar" style="width: 40px;height: 40px;border-radius:25px"/>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small"
                       type="success"
                       text
                       :icon="Edit"
                       @click="handleEdit(scope.row)"
            >修改</el-button>
            <el-button
                size="small"
                type="danger"
                text
                :icon="Delete"
                @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination  :total="total" @pageChange="page"></Pagination>

      <el-dialog
          v-model="dialogVisible"
          :title="title"
          width="500px">
        <el-form  ref="form"
                  :rules="rules"
                  :label-position="labelPosition"
                  label-width="80px"
                  :model="ruleForm" >

          <div style="width: 100%;display: flex;justify-content: center;align-items: center;padding-bottom: 20px;">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="file.headers"
                :action="file.uploadFileUrl"
            >
              <img v-if="ruleForm.avatar!==''" :src="ruleForm.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="ruleForm.nickname" />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="type===1">
            <el-input v-model="ruleForm.password"  type="password"/>
          </el-form-item>
<!--          <el-form-item label="手机号" prop="phone">-->
<!--            <el-input v-model="ruleForm.phone" />-->
<!--          </el-form-item>-->

          <el-form-item label="性别" prop="sex">
            <el-select v-model="ruleForm.sex" placeholder="请选择性别" style="width: 100%">
              <el-option
                  v-for="item in sex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="角色" prop="roleName">
            <el-select v-model="ruleForm.roleName" clearable placeholder="请选择角色" style="width: 100%">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script  lang="ts" setup>
import { Search,Refresh,Plus,Edit,Delete } from '@element-plus/icons-vue'

import Pagination from '@/components/pagination.vue';
import { onMounted,reactive, ref } from 'vue';
import {listUser,adduser,edituser,deleteuser} from "@/api/user";
import type { FormInstance, FormRules } from 'element-plus'
import {roles} from "@/api/role";
import type { UploadProps } from 'element-plus'
import {ElMessage, ElMessageBox} from "element-plus";
const labelPosition = ref('right');
const type = ref(1);
const list = ref([]);
const total = ref(0);
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref('');
const form = ref(null);

interface RoleOption {
  value: number;
  label: string;
}

const options = ref<RoleOption[]>([]);

const file =reactive({
  uploadFileUrl: "http://localhost:8001" + '/upload',
  headers: {
    Authorization: localStorage.getItem("token"),
  },
})
const sex = [
  {
    value: '0',
    label: '男',
  },
  {
    value: '1',
    label: '女',
  },
]
const ruleForm = reactive({
  id: null,
  username: null,
  password: '123456',
  nickname: null,
  avatar: '',
  sex: '',
  phone: null,
  roleName: null as null | number,
});
const query = reactive({
  pageNum:1,
  pageSize:10,
  username:null,
});

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  roleName:[
    { required: true, message: '请选择角色', trigger: 'blur' },
  ]
})
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.avatar = response.data.urlIp
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
const page = (e)=>{
  query.pageNum = e.currentPage;
  query.pageSize = e.pageSize;
  getlist()
}

const handleAdd = () => {
  title.value = '添加'
  dialogVisible.value = true
  type.value = 1;
  reset();
}
const reset = () => {
  ruleForm.id = null;
  ruleForm.username = null;
  ruleForm.password = '123456';
  ruleForm.sex = '';
  ruleForm.phone = null;
  ruleForm.nickname = null;
  ruleForm.roleName = null;
  ruleForm.avatar = '';
}

const handleQuery = () => {
  getlist()
}

const resetQuery = () => {
  query.username = null
  getlist()
}

const getlist = () => {
  loading.value = true;
  listUser(query).then(res=>{
    list.value = res.data;
    total.value = res.total;
    loading.value = false;
  })
}

const submitForm = () => {
  form.value.validate(valid=>{
    if (valid){
      if (type.value == 1){
        //添加
        adduser(ruleForm).then(res=>{
          getlist();
          dialogVisible.value = false;
        })
      }else {
        //修改

        edituser(ruleForm).then(res=>{
          getlist();
          dialogVisible.value = false;
        })
      }
    }
  })
}
const handleDelete = (data)=>{
  ElMessageBox.confirm(
      '确定要删除吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteuser(data.id).then(res=>{
          getlist();
          dialogVisible.value = false;
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        })

      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}

const handleEdit = (data)=>{
  title.value = "修改";
  dialogVisible.value = true;
  type.value = 2;
  getform(data)
}

const getform = (data)=>{
  ruleForm.id = data.id;
  ruleForm.username = data.username;
  ruleForm.sex = data.sex === '男' ? '0' : '1';
  ruleForm.phone = data.phone;
  ruleForm.nickname = data.nickname;
  ruleForm.roleName = data.rid*1;
  ruleForm.avatar = data.avatar;
}

const getroles = () =>{
  roles().then(res=>{
    options.value =  res.data
  })
}

onMounted(()=>{
  getlist();
  getroles();
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  border-radius: 25px;

}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>
